<?php

class ResourceTask extends \Formax\CLI\Task
{

    public function registerOptions()
    {
        $this
            ->registerOption('generate-lang', 'gl', false, false, '生成语言包文件')
            ->registerOption('lang', 'l', false, false, '指定语言');
    }

    public function mainAction()
    {
        if ($this->args->get('generate-lang')) {
            $this->generateLang();
        }
    }

    public function generateLang()
    {
        $data = array();
        foreach (config('acl.resources') as $category => $childs) {
            $data["r.$category"] = $category;
            foreach ($childs as $ident => $accesses) {
                $data["r.$category.$ident"] = $ident;
                foreach (explode(',', $accesses) as $access) {
                    $data["r.$category.$ident.$access"] = $access;
                }
            }
        }

        if ($this->args->get('lang')) {
            $this->_writeLangFile($data, $lang);
        } else {
            foreach (config('application.i18n.supports') as $lang => $text) {
                $this->_writeLangFile($data, $lang);
            }
        }
    }

    protected function _writeLangFile(array $data, $lang)
    {
        service('i18n')->import('acl.resource');
        foreach ($data as $key => & $val) {
            $translate = __($key, null, $lang);
            if ($translate === $key) {
                $val = str_replace(array('_', '-', '.'), ' ', $val);
                $val = implode(' ', array_map('ucfirst', explode(' ', $val)));
            } else {
                $val = $translate;
            }
        }

        $content = preg_replace('~\n  ~', "\n    ", var_export($data, true));
        $content = str_replace('array (', "<?php\n\nreturn array(", $content) . ";";
        $file = config('application.i18n.directory') . "/$lang/acl/resource.php";

        $dir = dirname($file);

        if (! is_dir($dir) && mkdir($dir, 0777)) {
            return cli_output('创建目录失败: '. $dir, 'error');
        }

        if (file_put_contents($file, $content)) {
            return cli_output("ACL 语言包：'$file' 写入成功", 'success');
        }

        return cli_output("ACL 语言包：'$file' 写入失败", 'error');
    }

}
